#!/usr/bin/python

import sqlite3 
import hashlib
import pyotp 
from dateutil.relativedelta import relativedelta
import datetime
import getpass

conn=sqlite3.connect('openvpn.db')
cur=conn.cursor()
while "username" not in globals():
    username=input("请输入用户名:")
    cur.execute("SELECT username FROM user WHERE username = '%s' " %(username))
    user=cur.fetchone()
    if user:
        print("用户名已存在!,请重新输入")
        del username
while "passwd" not in globals():
    passwd=getpass.getpass("请输入密码:")
    passwd1=getpass.getpass("再输入密码:")
    if passwd != passwd1 or not passwd :
        print("密码为空或不一致!")
        del passwd,passwd1
passwd=hashlib.md5(passwd.encode('utf8')).hexdigest()        
email=input("输入邮箱地址:") or "test@163.com"
salt=pyotp.random_base32()[0:16]
expires=(datetime.datetime.now()+relativedelta(years=2)).timestamp()
sql='insert into user(username,password,email,salt,expires) values(?,?,?,?,?)'
try:
    cur.execute(sql,(username,passwd,email,salt,expires))
    conn.commit()
    print("添加成功")
except Exception as r:
    print("添加失败 %s" %(r))
cur.close()
conn.close()

